package com.xb.ai.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xb.ai.common.PageResponse;
import com.xb.ai.common.PageRequest;
import com.xb.ai.constant.ErrorMessage;
import com.xb.ai.entity.po.Webpage;
import com.xb.ai.entity.vo.WebpagePage;
import com.xb.ai.exception.BusinessException;
import com.xb.ai.mapper.WebpageMapper;
import com.xb.ai.service.IWebpageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;


@Service
public class WebpageServiceImpl extends ServiceImpl<WebpageMapper, Webpage>
        implements IWebpageService {

    @Value("${webpage.zip.directory:#{systemProperties['user.dir'] + '/webpages'}}")
    private String webpageZipDirectory;

    /**
     * 获取网页列表
     * @return 网页信息
     */
    @Override
    public PageResponse<WebpagePage> getWebPageList(PageRequest pageRequest) {
        int current = pageRequest.getCurrent();
        int pageSize = pageRequest.getPageSize();

        Page<Webpage> page = lambdaQuery()
                .select(Webpage::getId, Webpage::getWebpageTitle, Webpage::getWebpageUrl)
                .page(new Page<>(current, pageSize));
        if (page == null) {
            return new PageResponse<>();
        }
        List<Webpage> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return new PageResponse<>();
        }
        List<WebpagePage> webpagePages = BeanUtil.copyToList(records, WebpagePage.class);
        PageResponse<WebpagePage> pageResponse = new PageResponse<>();
        pageResponse.setData(webpagePages);
        pageResponse.setPages(page.getPages());
        pageResponse.setTotal(page.getTotal());
        return pageResponse;
    }

    /**
     * 获取网页对应的ZIP文件
     * @param id 网页ID
     * @return ZIP文件对象
     */
    @Override
    public File getWebpageZipFile(Long id) {
        Webpage webpage = getById(id);
        if (webpage == null) {
            throw new BusinessException(ErrorMessage.DATA_NOT_FOUND_ERROR);
        }
        // 获取安全的文件名（去除特殊字符）
        String safeFileName = getSafeFileName(webpage.getWebpageTitle());
        // 使用配置的目录路径
        File zipFile = Paths.get(webpageZipDirectory, safeFileName + ".zip").toFile();

        if (!zipFile.exists()) {
            throw new BusinessException(ErrorMessage.DATA_NOT_FOUND_ERROR);
        }
        return zipFile;
    }

    /**
     * 获取安全的文件名，移除不安全字符
     */
    private String getSafeFileName(String fileName) {
        if (fileName == null || fileName.trim().isEmpty()) {
            return "unnamed";
        }
        // 移除文件名中的非法字符，替换为下划线
        return fileName.replaceAll("[\\\\/:*?\"<>|]", "_");
    }
}




